<template>
  <div>
    <el-select ref="selectTree" v-model="value" class="main-select-tree" style="width: 100%;">
      <el-option v-for="(item,index) in options" :key="index" :label="item.label" :value="item.value" style="display: none;" />
      <el-tree
        ref="selecteltree"
        class="main-select-el-tree"
        :data="datas"
        node-key="id"
        highlight-current
        :props="defaultProps"
        :current-node-key="value"
        :expand-on-click-node="expandOnClickNode"
        default-expand-all
        @node-click="handleNodeClick"
      />
    </el-select>
  </div>
</template>

<script>
export default {
  props: {
    formData: {
      type: Array,
      default() {
        return []
      }
    },
    selectedValue: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      value: '',
      expandOnClickNode: true,
      options: [],
      datas: [],
      defaultProps: {
        children: 'children',
        label: 'dictKey',
        disabled: function(data, node) {
          if (node.isLeaf == '0') {
            return true
          } else if (node.isLeaf == '1') {
            return false
          }
        }
      }
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        this.datas = newVal
        this.options = this.convertData(this.datas)
      }
    },
    selectedValue: {
      handler(newVal) {
        if (newVal) {
          this.value = newVal
        } else {
          this.value = undefined
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.datas = this.formData
  },
  methods: {
    //  转换数据格式
    convertData(data, arr = []) {
      const treeArr = []
      if (data.length > 0) {
        data.forEach(item => {
          treeArr.push({ label: item.dictKey, value: item.dictCode })
          if (item.children.length > 0) {
            this.convertData(item.children, arr)
          }
        })
        arr.push(...treeArr)
        return arr
      } else {
        return arr
      }
    },
    handleNodeClick(node) {
      if (node.isLeaf == '0') {
        this.$message.error('当前节点不允许选择')
      } else {
        this.value = node.dictCode
        this.$emit('handleNodeClick', this.value)
        this.$refs.selectTree.blur()
      }
    }
  }
}
</script>
<style>
.main-select-el-tree .el-tree-node .is-current > .el-tree-node__content{font-weight: bold; color: #409eff;}
.main-select-el-tree .el-tree-node.is-current > .el-tree-node__content{font-weight: bold; color: #409eff;}
.el-tree-node__label{
  width:400px !important;
}
</style>
